package me.hekr.iotos.softgateway.northProxy;

import me.hekr.iotos.softgateway.common.constant.Constants;
import me.hekr.iotos.softgateway.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.tio.utils.jfinal.P;

/** 软件网关连接类 调用connect方法用来将软件网关连接至IoTOS */
@Slf4j
public class ProxyConnectService {

  public MqttClient client;

  public static String UP_TOPIC = "up/dev/" + ProxyService.DEV_PK + "/" + ProxyService.DEV_ID;

  public static String DOWN_TOPIC =
      "down" + "/dev/" + ProxyService.DEV_PK + "/" + ProxyService.DEV_ID;
  /** 软件网关的clientId */
  public static String CLIENT_ID = "dev:" + ProxyService.DEV_PK + ":" + ProxyService.DEV_ID;

  public static final String USER_NAME = Constants.HASH_METHOD + ":" + Constants.RANDOM;

  public static final String HOST = "tcp://" + P.get("iotos.host");

  public ProxyConnectService() throws MqttException {
    // MemoryPersistence设置clientId的保存形式，默认为以内存保存
    client = new MqttClient(HOST, CLIENT_ID, new MemoryPersistence());
    connect();
  }

  /** 订阅一个主题 */
  public void connect() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(true);
    options.setUserName(USER_NAME);
    options.setPassword(ProxyService.getPassword().toCharArray());
    // 设置超时时间
    options.setConnectionTimeout(10);
    // 设置会话心跳时间
    options.setKeepAliveInterval(20);
    try {
      client.setCallback(new ProxyCallbackService());
      client.connect(options);
      // 订阅
      client.subscribe(DOWN_TOPIC, 0);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * @param message
   * @throws MqttPersistenceException
   * @throws MqttException
   */
  public void publish(Object message) throws MqttPersistenceException, MqttException {
    client.publish(UP_TOPIC, new MqttMessage(JsonUtil.toBytes(message)));
    if (log.isInfoEnabled()) {
      log.info("发送消息成功：{}", JsonUtil.toJson(message));
    }
  }

  /** 获取网关在线状态 */
  public boolean isConnected() {
    return client.isConnected();
  }
}
